﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using P113_GtMotion;
namespace GTSDemo.ViewModels
{
    /// <summary>
    /// 硬件实例的助手类
    /// </summary>
    internal class HardwareHelper
    {
        private static HardwareHelper _helper = new HardwareHelper();
        public bool _isVirtual { get; private set; } = false;
        /// <summary>
        /// 卡数
        /// </summary>
        public int CardCount { get; set; }
        /// <summary>
        /// 当前的卡索引
        /// </summary>
        public int CurrentCardIndex { get; set; }
        internal Motion Motion { get; private set; }
        internal P113_GtMotion.IO _gtIO { get; private set; }
        internal List<Motor> Motors { get; private set; } = new List<Motor>();
        internal List<P110_BaseMotion.Input> Inputs { get; private set; } = new List<P110_BaseMotion.Input>();
        internal List<P110_BaseMotion.Output> Outputs { get; private set; } = new List<P110_BaseMotion.Output>();
        private HardwareHelper()
        {

        }
        internal static HardwareHelper GetHardwareHelper()
        {
            return _helper;
        }
        internal void Initialization()
        {
            if (CardCount <= 0) _isVirtual = true;
            Motion = new Motion(CardCount <= 0 ? 1 : CardCount) { Virtual = _isVirtual };
            _gtIO = new IO();
            for (uint i = 0; i < CardCount; i++)
            {
                for (uint k = 0; k < 8; k++)
                {
                    Motors.Add(new Motor(i, k) { Alias = $"Motor{k + 1}" });
                }
                for (int inputIndex = 0; inputIndex < 16; inputIndex++)
                {
                    Inputs.Add(new P110_BaseMotion.Input(_gtIO)
                    {
                        Alias = $"DI{inputIndex}",
                        Bit = (short)((i + 1) * 100 + inputIndex),                        
                    }) ;
                }
                for (int outputIndex = 0; outputIndex < 16; outputIndex++)
                {
                    Outputs.Add(new P110_BaseMotion.Output(_gtIO)
                    {
                        Alias = $"DI{outputIndex}",
                        Bit = (short)((i + 1) * 100 + outputIndex),
                    });
                }
            }            
            Motion.Initialize();
        }
        public List<Motor> GetCurrentMotors()
        {
            return Motors.Where(s => s.CardIndex == CurrentCardIndex).ToList();
        }
        public List<P110_BaseMotion.Input> GetCurrentInputs()
        {
            return Inputs.Where(s => s.Bit / 100 - 1 == CurrentCardIndex).ToList();
        }
        public List<P110_BaseMotion.Output> GetCurrentOutpus()
        {
            return Outputs.Where(s => s.Bit / 100 - 1 == CurrentCardIndex).ToList();
        }
    }
}
